/**
 * 首页模块
 * 默认模块名: main
 * @return {[object]}  [ 返回一个对象 ]
 */
let storage = bui.storage();
let ggArrr = []
let timer;

let ROLL_SPEED = 150
let noticeList1;
let noticeList2;
let listWrapper;
let noticeTimer;
let org;
let token;
let language;
let translate;
let ids
loader.define(function(require, exports, module, global) {
    var pageview = {};

    // 模块初始化定义
    pageview.init = function() {
        translate = global.translate
        language = storage.get("language", 0)
        if (!language) {
            language = 'chinese_simplified'
        }
        try {
            translate.selectLanguageTag.show = false;
            translate.ignore.id.push('languageHead')
            let curLanguage = translate.language.getCurrent()
            if (curLanguage !== language) {
                translate.changeLanguage(language)
            }
            translate.execute();
        }catch (e) {
            console.log("切换语言报错")
        }
        let languageArr = storage.get('languageArr',0)
        let html = ''
        let html2 = '<select class="languageSelect" id="languageSelectId">\n'
        if (language !== 'chinese_simplified' && language !== 'english') {
            languageArr.forEach(lan => {
                if (lan.id === language) {
                    html += '<span class="language" id="'+lan.id+'">'+lan.name+'</span>|'
                } else {
                    html2 += '<option value="'+lan.id+'">'+lan.name+'</option>'
                }
            })
        } else {
            languageArr.forEach(lan => {
                html2 += '<option value="'+lan.id+'">'+lan.name+'</option>'
            })
        }
        html+= '<span class="language" id="english">English</span>|<span class="language" id="chinese_simplified">简体中文</span>'
        router.$("#languageContent").html(html + html2 + "</select>")

        if (language === "chinese_simplified") {
            router.$("#gz").css("font-size", "")
            router.$("#fb").css("font-size", "")
            router.$('#notice-list').css("font-size", "");
            router.$('#listTitle').css("font-size", ".34rem");
        } else {
            router.$("#gz").css("font-size", ".23rem")
            router.$("#fb").css("font-size", ".23rem")
            router.$('#notice-list').css("font-size", ".22rem");
            router.$('#listTitle').css("font-size", ".26rem");
        }
        router.$(".language").click(function () {
            let selectId = $(this).attr('id')
            if (selectId !== language) {
                storage.set("language", selectId)
                location.reload()
            }
        })
        router.$("#languageSelectId").val("");
        router.$("#languageSelectId").change(function () {
            let selectId = $(this).val()
            if (selectId !== language) {
                storage.set("language", selectId)
                location.reload()
            }
        })

        let uiLoading
        // let uiLoading = bui.loading({
        //     appendTo:"#mainLoading",
        //     width: 40,
        //     height: 40,
        //     opacity: 0.5,
        //     text:"加载中。。。",
        //     autoClose: false
        // });
        // uiLoading.show()

        if (isMobile()) {
            router.$("#searchK").css("padding-top", "0");
            router.$("#searchPic").css("margin-top", "3px");
        }

        ggArrr = []
        token = storage.get("token",0)
        org = storage.get("org",0)
        //分享设置0未设置1已设置
        let shareSign = '0'

        let url = window.location.href
        let params = url.split("?")
        url = params[0]
        if (params.length === 1 || (params.length > 1 && params[1].indexOf('&') > -1)) {
            if (org) {
                // 获取当前URL
                let url1 = new URL(url);
                // 创建URLSearchParams对象
                let params1 = new URLSearchParams(url1.search);
                // 修改指定参数的值
                params1.set('city', org.id);
                // 将修改后的参数设置回URL
                url1.search = params1.toString();
                // 使用history.replaceState()方法修改URL，而不刷新页面
                history.replaceState(null, '', url1.href)

                init(global, uiLoading,shareSign)
            } else {
                bui.ajax({
                    url: global.api.getCityById,
                    data: {id: 169},
                    method: "POST"
                }).then(function(res){
                    org = res.data
                    storage.set("org", res.data)
                    // 获取当前URL
                    let url1 = new URL(url);
                    // 创建URLSearchParams对象
                    let params1 = new URLSearchParams(url1.search);
                    // 修改指定参数的值
                    params1.set('city', org.id);
                    // 将修改后的参数设置回URL
                    url1.search = params1.toString();
                    // 使用history.replaceState()方法修改URL，而不刷新页面
                    history.replaceState(null, '', url1.href)

                    init(global, uiLoading,shareSign)
                })
            }
        } else {
            let orgid = params[1].split("=")[1]
            orgid = orgid.split("#")[0]
            bui.ajax({
                url: global.api.getCityById,
                data: {id: orgid},
                method: "POST"
            }).then(function(res){
                org = res.data
                storage.set("org", res.data)
                init(global, uiLoading,shareSign)
            })
        }
    }

    // 初始化
    pageview.init();

    // 输出模块
    return pageview;
})


function rollStart() {
    if (Math.abs(_subStr(listWrapper.css('top'))) >= noticeList1.height()) {
        listWrapper.css('top', -30)
    } else {
        var top = listWrapper.css('top');
        listWrapper.css('top', _subStr(top) - 1)
    }
}
// 截取px前数值
function _subStr(str) {
    if (str) {
        var index = str.indexOf('px');
        if (index > -1) {
            return parseFloat(str.substr(0, index + 1))
        }
    }
}

function formatDate(time) {
    let date = new Date(time * 1000);
    // let now = new Date();
    // let days=parseInt((now - date) / (1000 * 60 * 60* 24) + '');
    // if (days > 7){
        let Y = date.getFullYear() + '-';
        let M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        let D = (date.getDate() < 10 ? '0'+(date.getDate()) : date.getDate()) + ' ';
        let h = (date.getHours() < 10 ? '0'+(date.getHours()) : date.getHours()) + ':';
        let m = (date.getMinutes() < 10 ? '0'+(date.getMinutes()) : date.getMinutes()) + ':';
        let s = (date.getSeconds() < 10 ? '0'+(date.getSeconds()) : date.getSeconds());
        return Y+M+D+h+m+s
    // } else if (days < 1) {
    //     let hour=parseInt((now - date) / (1000 * 60 * 60) + '');
    //     return hour + "小时前"
    // }
    // return days + "天前"
}

function isMobile() {
    let userAgentInfo = navigator.userAgent;

    let mobileAgents = ["Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod"];

    let mobile_flag = false;

    let ua = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        mobile_flag = true
    } else {
        //根据userAgent判断是否是手机
        for (let v = 0; v < mobileAgents.length; v++) {
            if (userAgentInfo.indexOf(mobileAgents[v]) > 0) {
                mobile_flag = true;
                break;
            }
        }
    }

    return mobile_flag;
}

function isWeiXin() {
    let ua = navigator.userAgent.toLowerCase()
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
        return true
    } else {
        return false
    }
}

function init(global, uiLoading, shareSign) {
    ids = []
    router.$("#countryStr").html(org.description)
    router.$("#listTitle").html(org.description+"最新消息")

    if (org.qrcode) {
        router.$("#qrcode").attr('src', org.qrcode)
    } else {
        router.$("#qrcode").attr('src', 'images/qrcode.jpg')
    }

    router.$("#menu").click(function () {
        router.replace({url: "pages/country/country.html"});
    })

    // 自定义居中弹出框
    let gzDialog = bui.dialog({
        id: "#gzDialog",
        height: 300,
        // mask: false,
        callback: function(e) {}
    });

    // let menu = storage.get("menu" + org.id)
    // if (menu && menu.length > 0) {
    //     let menuData = menu
    //     let html = ""
    //     let tabHtml = ""
    //     menuData.forEach((da, index) => {
    //         if (index % 10 == 0) {
    //             if (index > 0) {
    //                 html += '</ul></li>'
    //             }
    //             html += '<li><ul class="index-nav bui-fluid-space">'
    //
    //             tabHtml+= '<li></li>'
    //         }
    //
    //         html += '<li class="bui-btn bui-box-vertical menuSpan menuChildren" id="'+da.id+'" name="'+da.name+'">\n' +
    //             '                                <div class="icons-round">\n' +
    //             '                                    <img src="'+da.imgUrl+'" style="width: 100%; height: 100%;">\n' +
    //             '                                </div>\n' +
    //             '                                <div class="span1">'+da.name+'</div>\n' +
    //             '                            </li>'
    //     })
    //
    //     if (menuData.length % 10 == 0) {
    //         html += '</ul></li><li><ul class="index-nav bui-fluid-space">'
    //         tabHtml+= '<li></li>'
    //     }
    //     html += '<li class="bui-btn bui-box-vertical menuSpan menuChildrenGd">\n' +
    //         '                                <div class="icons-round">\n' +
    //         '                                    <img src="images/gd.png" style="width: 100%; height: 100%;">\n' +
    //         '                                </div>\n' +
    //         '                                <div class="span1">更多分类</div>\n' +
    //         '                            </li>'
    //     html += '     </ul></li>'
    //     router.$("#menuModel").html(html)
    //     router.$("#menuHead").html(tabHtml)
    //
    //     // 菜单初始化
    //     bui.slide({
    //         id: "#slide",
    //         height: 390
    //     });
    //     try {
    //         translate.execute();
    //     }catch (e) {
    //         console.log("切换语言报错")
    //     }
    //     //查询菜单
    //     bui.ajax({
    //         url: global.api.getMenuList,
    //         data: {city: org.id, country: org.parent, place: '1'},
    //         method: "POST"
    //     }).then(function(res) {
    //         let menuData = res.data
    //         storage.set("menu" + org.id, menuData)
    //     })
    // } else {
        //查询菜单
        bui.ajax({
            url: global.api.getMenuList,
            data: {city: org.id, country: org.parent, place: '1'},
            method: "POST"
        }).then(function(res){
            let menuData = res.data
            if (menuData && menuData.length > 0) {
                let html = ""
                let tabHtml = ""
                menuData.forEach((da, index) => {
                    if (index % 10 == 0) {
                        if (index > 0) {
                            html += '</ul></li>'
                        }
                        html += '<li><ul class="index-nav bui-fluid-space">'

                        tabHtml+= '<li></li>'
                    }

                    html += '<li class="bui-btn bui-box-vertical menuSpan menuChildren" id="'+da.id+'" name="'+da.name+'">\n' +
                        '                                <div class="icons-round">\n' +
                        '                                    <img src="'+da.imgUrl+'" style="width: 100%; height: 100%;">\n' +
                        '                                </div>\n' +
                        '                                <div class="span1">'+da.name+'</div>\n' +
                        '                            </li>'
                })

                if (menuData.length % 10 == 0) {
                    html += '</ul></li><li><ul class="index-nav bui-fluid-space">'
                    tabHtml+= '<li></li>'
                }
                html += '<li class="bui-btn bui-box-vertical menuSpan menuChildrenGd">\n' +
                    '                                <div class="icons-round">\n' +
                    '                                    <img src="images/gd.png" style="width: 100%; height: 100%;">\n' +
                    '                                </div>\n' +
                    '                                <div class="span1">更多分类</div>\n' +
                    '                            </li>'
                html += '     </ul></li>'
                router.$("#menuModel").html(html)
                router.$("#menuHead").html(tabHtml)

                // 菜单初始化
                bui.slide({
                    id: "#slide",
                    height: 390
                });
                try {
                    translate.execute();
                }catch (e) {
                    console.log("切换语言报错")
                }
            }

            // uiLoading.stop()
        })
    // }


    //查询综合
    bui.ajax({
        url: global.api.getZhList,
        data: {city: org.id, country: org.parent,cityStr: org.name, place: '1'},
        method: "POST"
    }).then(function(res){
        let data = res.data
        ggArrr = data.ggData
        router.$("#advertiseK").hide()
        if (ggArrr && ggArrr.length > 0) {
            let index = Math.floor(Math.random()*ggArrr.length)
            router.$("#advertise").attr("src", ggArrr[index].imgUrl)
            router.$("#advertiseK").attr("name", ggArrr[index].article + '~' + ggArrr[index].glUserid)
            router.$("#advertiseK").show()
        }

        let arr = data.noticeData
        if (arr) {
            if (noticeTimer) {
                clearInterval(noticeTimer)
            }

            let html = ''
            $.each(arr, function (index, value) {
                html += '<li class="newContent" name="'+value.id+'~'+value.glUserid+'">'+value.title+'</li>'
            })
            router.$("#notice-list").html(html)
            try {
                translate.execute();
            }catch (e) {
                console.log("切换语言报错")
            }
            router.$(".newContent").click(function () {
                let param = router.$(this).attr("name")
                let params = param.split('~')
                let id = params[0]
                let glUserid = params[1]
                // if (noticeTimer) {
                //     clearInterval(noticeTimer)
                // }
                router.load({ url: "pages/articleInfo/articleInfo.html", param: {tzSign: '0',id: id, glUserid: glUserid}});
            })
            noticeList1 = router.$('#notice-list');
            noticeList2 = router.$('#notice-list-2');
            listWrapper = router.$('#list-wrapper');
            noticeList2.html(noticeList1.html())
            listWrapper.css('top', -30)
            noticeTimer = setInterval(rollStart, ROLL_SPEED);
        }
    })

    // 查询需要缓存数据
    bui.ajax({
        url: global.api.getCountryTermList,
        method: "POST"
    }).then(function(res){
        let data = res.data
        if (data){
            let country = data.country
            let countryList = []
            country.forEach(coun => {
                if (coun.children && coun.children.length > 0) {
                    countryList.push({id: coun.id, description: coun.description})
                    storage.set("country" + coun.id, coun.children)
                }
            })
            storage.set("countryList", countryList)
            let term = data.term
            let termList = []
            term.forEach(ter => {
                if (ter.children && ter.children.length > 0) {
                    termList.push({id: ter.id, name: ter.name})
                    storage.set("term" + ter.id, ter.children)
                }
            })
            storage.set("termList", termList)
        }
    })

    router.$("#advertiseK").click(function () {
        let param = router.$(this).attr("name")
        let params = param.split('~')
        let id = params[0]
        let glUserid = params[1]
        router.replace({ url: "pages/articleInfo/articleInfo.html", param: {id: id, glUserid: glUserid}});
        // storage.set("article", param)
        // bui.load({ url: "pages/home/index.html"});
    })

    router.$("#gz").click(function () {
        gzDialog.open()
    })
    router.$("#fb").click(function () {
        if (token) {
            bui.ajax({
                url: global.api.verifyToken,
                method: "POST",
                headers: {Token: token}
            }).then(function(res){
                if (res.code != '200') {
                    storage.set("dlTz", '0')
                    router.replace({ url: "pages/login/login.html", param:{tzSign: '0'}});
                } else {
                    router.load({ url: "pages/fbZj/fbZj.html", param:{tzSign: '0'}});
                }
            })
        } else {
            storage.set("dlTz", '0')
            router.replace({ url: "pages/login/login.html", param:{tzSign: '0'}});
        }
    })

    router.$('#search').click(function(){
        router.load({url: "pages/search/search.html"});
    });


    bui.list({
        id: "#scrollList",
        uid: 'mainScrollList',
        url: global.api.getArticleList,
        pageSize: 10, // 当pageSize 小于返回的数据大小的时候,则认为是最后一页,接口返回的数据最好能返回空数组,而不是null
        data: {
            city: org.id,
            redisCity: org.name,
            country: org.parent,
            isduplicate: 0,
            'isfix': '1'
        },
        //如果分页的字段名不一样,通过field重新定义
        field: {
            page: "page",
            size: "limit",
            data: "data"
        },
        callback: function(e) {
            // e.target 为你当前点击的元素
            // e.currentTarget 为你当前点击的handle 整行

            let classStr = router.$(e.currentTarget).attr("class")
            let id = router.$(e.currentTarget).attr("id")
            let name = router.$(e.currentTarget).attr("name")
            if(classStr.indexOf("menuChildren") < 0 && classStr.indexOf("menuChildrenGd") < 0) {
                // if (noticeTimer) {
                //     clearInterval(noticeTimer)
                // }
                // router.replace({ url: "pages/articleInfo/articleInfo.html", param: {id: id, glUserid: name}});
                router.load({ url: "pages/articleInfo/articleInfo.html", param: {tzSign: '0',id: id, glUserid: name}});
            } else if (classStr.indexOf("menuChildrenGd") > -1){
                // if (noticeTimer) {
                //     clearInterval(noticeTimer)
                // }
                router.load({ url: "pages/typePage/typePage.html"});
            } else {
                // if (noticeTimer) {
                //     clearInterval(noticeTimer)
                // }
                storage.set('menCate', id + '-' + name + "-" + org.id)
                // router.load({ url: "pages/flPage/flPage.html",param:{tzSign: '0'}});
                bui.load({ url: "pages/flPage/flPage.html"});
            }
        },
        template: function(data) {
            let picClass = 'imgBJPC'
            if (isMobile()) {
                picClass = 'imgBJ'
            }

            let fontSize = '0.3rem'
            let fontSize2 = '0.24rem'
            let fontSize3 = '0.2rem'
            if (language !== "chinese_simplified") {
                fontSize = '0.22rem'
                fontSize2 = '0.18rem'
                fontSize3 = '0.12rem'
            }
            let html = "";
            let newIds = []
            data.forEach(function(el, index) {
                if (ids.indexOf(el.id) === -1) {
                    newIds.push(el.id)
                    let key = "articleInfo" + el.id
                    let article = storage.get(key,0)
                    if (!article) {
                        storage.set(key, el)
                    }

                    html += '<li class="bui-btn bui-box-vertical" id="'+el.id+'" name="'+el.glUserid+'">\n' +
                        '                            <div style="min-height: 60px">\n'
                    if (el.zd == '0') {
                        html += '                                <div class="zdK" style="font-size: '+fontSize+'">荐</div>\n'
                    }
                    html += '                                <p style="color: black;font-size: '+fontSize+';margin-bottom: 0.22rem">'+el.title+'</p>\n'

                    if (el.contentText) {
                        if (el.contentText) {
                            html += '                        <p style="color: rgb(120,120,120);font-size: '+fontSize3+';margin-bottom: 0.22rem">'+el.contentText.substring(0,100)
                            if(el.contentText.length > 100) {
                                html += '...'
                            }
                            html += '</p>\n'
                        }
                    }
                    html += '                                <p class="item-text">\n' +
                        '                                    <span class="listTab" style="font-size: '+fontSize2+'">'+el.cateStr+'</span>\n' +
                        '                                    <span style="font-size: '+fontSize2+'">\n' + formatDate(el.ptime) +
                        '                                    </span>\n' +
                        '                                    <span style="font-size: '+fontSize2+'">'+org.description+'</span>\n' +
                        '                                </p>\n' +
                        '                            </div>\n'+
                        '                            <div class="span1">\n'+
                        '                                <div class="bui-box">\n'
                    if (el.imgs && el.imgs.length > 0) {
                        let len = el.imgs.length > 3 ? 3 : el.imgs.length
                        for (let i = 0; i < len; i++) {
                            html +=  '                                    <div class="span1 '+picClass+'">\n' +
                                '                                        <img src="'+el.imgs[i]+'?x-oss-process=style/index" alt="">\n' +
                                '                                    </div>\n'
                        }

                        if (len < 3) {
                            for (let i = 0; i < 3- len; i++) {
                                html +=  '                                    <div class="span1 '+picClass+'">\n' +
                                    '                                    </div>\n'
                            }
                        }

                        html += '                                </div>\n' +
                            '                            </div>\n' +
                            '                        </li>'

                    } else {
                        html += '                        </li>'
                    }
                }
            });

            if (!html) {
                data.forEach(function(el, index) {
                    newIds.push(el.id)
                    let key = "articleInfo" + el.id
                    let article = storage.get(key,0)
                    if (!article) {
                        storage.set(key, el)
                    }

                    html += '<li class="bui-btn bui-box-vertical" id="'+el.id+'" name="'+el.glUserid+'">\n' +
                        '                            <div style="min-height: 60px">\n'
                    if (el.zd == '0') {
                        html += '                                <div class="zdK" style="font-size: '+fontSize+'">荐</div>\n'
                    }
                    html += '                                <p style="color: black;font-size: '+fontSize+';margin-bottom: 0.22rem">'+el.title+'</p>\n'

                    if (el.contentText) {
                        if (el.contentText) {
                            html += '                        <p style="color: rgb(120,120,120);font-size: '+fontSize3+';margin-bottom: 0.22rem">'+el.contentText.substring(0,100)
                            if(el.contentText.length > 100) {
                                html += '...'
                            }
                            html += '</p>\n'
                        }
                    }
                    html += '                                <p class="item-text">\n' +
                        '                                    <span class="listTab" style="font-size: '+fontSize2+'">'+el.cateStr+'</span>\n' +
                        '                                    <span style="font-size: '+fontSize2+'">\n' + formatDate(el.ptime) +
                        '                                    </span>\n' +
                        '                                    <span style="font-size: '+fontSize2+'">'+org.description+'</span>\n' +
                        '                                </p>\n' +
                        '                            </div>\n'+
                        '                            <div class="span1">\n'+
                        '                                <div class="bui-box">\n'
                    if (el.imgs && el.imgs.length > 0) {
                        let len = el.imgs.length > 3 ? 3 : el.imgs.length
                        for (let i = 0; i < len; i++) {
                            html +=  '                                    <div class="span1 '+picClass+'">\n' +
                                '                                        <img src="'+el.imgs[i]+'?x-oss-process=style/index" alt="">\n' +
                                '                                    </div>\n'
                        }

                        if (len < 3) {
                            for (let i = 0; i < 3- len; i++) {
                                html +=  '                                    <div class="span1 '+picClass+'">\n' +
                                    '                                    </div>\n'
                            }
                        }

                        html += '                                </div>\n' +
                            '                            </div>\n' +
                            '                        </li>'

                    } else {
                        html += '                        </li>'
                    }
                });
            }

            ids = newIds

            setTimeout(function () {
                try {
                    translate.execute();
                }catch (e) {
                    console.log("切换语言报错")
                }
            },1000)

            return html;
        }
    })

    if (isWeiXin()) {
        router.$("#position").show()
        let userPositionConfirm = storage.get("userPositionConfirm")
        let dwCity = storage.get("dwCity")
        if (!userPositionConfirm || userPositionConfirm == '0') {
            if (!dwCity) {
                dwCity = '定位中。。。'
            }
        } else {
            dwCity = "未授权定位"
            router.$("#position").click(function () {
                router.$("#position").text('定位中。。。')
                wx.getLocation({
                    type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                    success: function (res) {
                        storage.set("userPositionConfirm", "0")
                        let latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                        let longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。

                        bui.ajax({
                            url: global.api.getCityByLocal,
                            data: {local: longitude + ',' +  latitude},
                            method: "POST"
                        }).then(function(res){
                            let nOrg = res.data
                            if (nOrg.id) {
                                bui.confirm({
                                    "title": "",
                                    "height": 460,
                                    "content": '<div class="bui-box-center"><div><p>当前城市在'+nOrg.description+',是否需要切换</p></div></div>',
                                    "buttons": ["取消","确定"],
                                    callback: function(e) {
                                        //this 是指点击的按钮
                                        let text = router.$(e.target).text();

                                        if (text == "确定") {
                                            org = nOrg
                                            storage.set("org", nOrg)
                                            init(global, uiLoading, shareSign)
                                        }
                                        this.close()
                                    }
                                });
                            }
                            router.$("#position").text(nOrg.description)
                            storage.set("dwCity", nOrg.description)
                        })
                    },
                    fail: function (e) {
                        storage.set("userPositionConfirm", "1")
                        router.$("#position").html('未授权定位')
                    }
                });
            })
        }
        router.$("#position").text(dwCity)
        bui.ajax({
            url: global.api.getWxConfig,
            data: {url: location.href.split('#')[0]},
            method: "GET"
        }).then(function(res){
            if (res.code == '200') {
                let data = res.data
                wx.config({
                    debug: false,
                    appId: data.appId,
                    timestamp: data.timestamp,
                    nonceStr: data.nonceStr,
                    signature: data.signature,
                    jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage",'checkJsApi', 'getLocation']
                })
                // wx.checkJsApi({
                //     jsApiList: ['getLocation'],
                //     success: function (res) {
                //         console.log(res)
                //         if (res.checkResult.getLocation == false) {
                //             bui.alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
                //             return;
                //         }
                //     },
                //     fail: function (res) {
                //         console.info('checkJsApi fail=')
                //     }
                // });
                wx.ready(function () {
                    if (!userPositionConfirm || userPositionConfirm == '0') {
                        wx.getLocation({
                            type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                            success: function (res) {
                                storage.set("userPositionConfirm", "0")
                                let latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                                let longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。

                                bui.ajax({
                                    url: global.api.getCityByLocal,
                                    data: {local: longitude + ',' +  latitude},
                                    method: "POST"
                                }).then(function(res){
                                    let nOrg = res.data
                                    if (nOrg.id && dwCity != nOrg.description) {
                                        bui.confirm({
                                            "title": "",
                                            "height": 460,
                                            "content": '<div class="bui-box-center"><div><p>当前城市在'+nOrg.description+',是否需要切换</p></div></div>',
                                            "buttons": ["取消","确定"],
                                            callback: function(e) {
                                                //this 是指点击的按钮
                                                let text = router.$(e.target).text();

                                                if (text == "确定") {
                                                    org = nOrg
                                                    storage.set("org", nOrg)
                                                    init(global, uiLoading, shareSign)
                                                }
                                                this.close()
                                            }
                                        });
                                    }
                                    router.$("#position").text(nOrg.description)
                                    storage.set("dwCity", nOrg.description)
                                })
                            },
                            fail: function (e) {
                                storage.set("userPositionConfirm", "1")
                                router.$("#position").html('未授权定位')
                            }
                        });
                    }
                    wx.onMenuShareAppMessage({
                        title: "海外同城"+org.description+"信息分类网站", // 分享标题
                        desc: '海外同城'+org.description+'信息分类网，为你提供房产服务、招聘信息、本地生活服务、', // 分享描述
                        link: 'https://ty.happindo.com?org=' + org.id + "&nonce=" + translate.generateRandomString(4) + "#main", // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: org.shareImage, // 分享图标
                        type: '', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '',
                        success: function () {
                        }
                    })
                    wx.onMenuShareTimeline({
                        title: "海外同城"+org.description+"信息分类网站", // 分享标题
                        desc: '海外同城'+org.description+'信息分类网，为你提供房产服务、招聘信息、本地生活服务、',
                        link: 'https://ty.happindo.com?org=' + org.id + "&nonce=" + translate.generateRandomString(4) + "#main", // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: org.shareImage, // 分享图标
                        success: function () {
                        }
                    })
                })
            } else {
                // bui.alert(res.msg)
            }
        })
    }
}
